package com.xm.servlet.background.orders;

import com.xm.service.background.CommodityWarehouseService;
import com.xm.service.background.OrdersService;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单发货
 * @author 康文程
 * @date 2024-1-11
 * asyncSupported 允许异步请求
 */
@WebServlet(urlPatterns = "/orders/shipments", asyncSupported = true)
public class OrdersShipmentsServlet extends HttpServlet {
    /**
     * 修改商品库存
     */
    private final CommodityWarehouseService service = new CommodityWarehouseService();
    /**
     * 修改订单
     */
    private final OrdersService ordersService = new OrdersService();
    /**
     * 线程池，用于异步处理请求
     */
    private final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            10,
            100,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),
            new OrdersShipmentsServlet.NamedThreadFactory("OrderShipmentsDateThread")
    );

    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        // 设置响应头
        resp.setContentType("text/html;charset=utf-8");

        // 获取请求参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        String commodityId = parameterMap.get("commodityId")[0];
        int quantity = Integer.parseInt(parameterMap.get("quantity")[0]);
        String orderId = parameterMap.get("trackingNumber")[0];
        int logisticsCompanieId = Integer.parseInt(parameterMap.get("logisticsCompanies")[0]);
        int logisticsStationId = Integer.parseInt(parameterMap.get("logisticsStation")[0]);
        int shippingMethod = Integer.parseInt(parameterMap.get("shippingMethod")[0]);

        // 开始异步处理请求
        AsyncContext context = req.startAsync();
        threadPool.submit(() -> {
            try {
                // 处理业务逻辑，更新库存
                boolean status = service.updateInventory(Integer.parseInt(commodityId), quantity);
                if (status){
                    //修改订单状态
                    boolean orderStatus = ordersService.updateOrderDetails(orderId, logisticsCompanieId
                            , logisticsStationId, 6, shippingMethod);
                    //如果修改订单状态失败则直接终止
                    if (!orderStatus){
                        return;
                    }
                }

                // 发送响应数据
                resp.getWriter().print(true);

                // 完成异步处理
                context.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 关闭线程池
     */
    @Override
    public void destroy() {
        threadPool.shutdown();
        super.destroy();
    }
    /**
     * 自定义ThreadFactory，用于指定有意义的线程名称
     */
    private static class NamedThreadFactory implements ThreadFactory {
        //线程名称
        private final String namePrefix;
        //计数器
        private final AtomicInteger count = new AtomicInteger(1);
        //创建线程
        public NamedThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread t = new Thread(r);
            //设置线程名称
            t.setName(namePrefix + "-" + count.getAndIncrement());
            return t;
        }
    }
}
